<?php
/**
 * FTP上传类，需要开启GD
 * 
 * @copyright 	Copyright (c) 2011 thinkapk.com All rights reserved.
 * @package 	ThinkAPK_Ftp
 * @link 		http://www.thinkapk.com/
 * @author 		richie <richbossman@163.com>
 * @version 	$Id: UpLoadFile.class.php 7494 2011-05-24 10:03:05Z richie $
 */
class ThinkAPK_Ftp_UpLoadFile extends ThinkAPK {
	
	//错误信息
	private $errmsg = '';
	//FTP信息
	private $ftpinfo;
	//FTP对象
	private $ftp;
	//FILES信息
	private $FILES;
	
	/**
	 * 单个文件上传
	 *
	 */
	function upLoadFileOne($file=array(), $dirname='pic'){
		$this->FILES = $file;
		
		if(!in_array($this->FILES['type'], array('image/gif', 'image/pjpeg', 'image/jpeg', 'image/x-png', 'image/png'))){
			$this->errmsg = '上传的文件类型不正确';
			return false;
		}
		
		if($this->connectFtp() == false){
			return false;
		}
		$dir = $this->getNewDir($dirname);
		
		$this->ftp->mkDirRecursive($dir);
		$filename = $dir.$this->getNewFileName();
		if($this->ftp->put($filename, $this->FILES['tmp_name'], FTP_BINARY)){
			return array('url' => $this->ftpinfo['domain'].$filename);
		}else{
			$this->errmsg = $this->ftp->getError();
			return false;
		}
	}
	
	/**
	 * 随机调取一个FTP信息
	 *
	 * @return array
	 */
	function randFtpServer(){
		$ftpServer = require CONFIG_COMMON_PATH.'ftps.php';
		$total = count($ftpServer);
		if($total == 0) return false;
		$key = rand(0, $total-1);
		if(!isset($ftpServer[$key])) return false;
		$this->ftpinfo = $ftpServer[$key];
		return true;
	}
	
	/**
	 * 连接FTP
	 *
	 * @return object
	 */
	function connectFtp(){
		if($this->randFtpServer() == false){
			$this->errmsg = 'FTP信息读取失败';
			return false;
		}
		$ftp = new ThinkAPK_Ftp($this->ftpinfo);
		if($ftp->getError()){
			$this->errmsg = $ftp->getError();
			return false;
		}
		$this->ftp = $ftp;
		return true;
	}
	
	/**
	 * 取得文件后缀
	 *
	 * @return array
	 */
	function getExt(){
		$pathinfo = pathinfo($this->FILES['name']);
		return isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
	}
	
	/**
	 * 取得新上传文件名
	 *
	 * @return string
	 */
	function getNewFileName(){
		$size = getimagesize($this->FILES['tmp_name']);
		return time().'-'.rand(0, 500).'-'.(isset($size[0])?$size[0]:'0').'x'.(isset($size[1])?$size[1]:'0').'.'.$this->getExt();
	}
	
	/**
	 * 取得新文件存放的目录
	 *
	 * @param string $dirname
	 * @return string
	 */
	function getNewDir($dirname='pic'){
		$md5 = md5($this->FILES['name']);
		return $dirname.'/'.$md5{0}.'/'.date('Ym', time()).'/'.date('d', time()).'/';
	}
	
	/**
	 * 取得错误信息
	 *
	 * @return string
	 */
	function getError(){
		return $this->errmsg;
	}
}
?>